package com.bnzj.core.util;

import java.security.SecureRandom;
import java.security.Security;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * AES对称加密
 * @author barry
 *
 */
public class SymmetricEncrypt {
	private static Logger log = LoggerFactory.getLogger(SymmetricEncrypt.class);
	
    private static final String AESTYPE ="AES/ECB/PKCS7Padding";
	
	private static String KEY = null;
    
	private static Cipher encipher = null;
	
	private static Cipher decipher = null;
	
    static {
        try {
            // 设置加密方案
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            encipher = Cipher.getInstance(AESTYPE, "BC");
            decipher = Cipher.getInstance(AESTYPE, "BC");
        } catch (Exception e) {
            log.error("", e);
        } // 创建密码器
    }
	
    public static void init(final String key) {
        try {
            KEY = key;
            // 初始化加密解密器
            SecretKeySpec keySpec = new SecretKeySpec(Base64.getDecoder().decode(key), "AES");
            encipher.init(Cipher.ENCRYPT_MODE, keySpec);
            decipher.init(Cipher.DECRYPT_MODE, keySpec);
        } catch (Exception e) {
            log.error("", e);
        }
    }
    
    public static String getKey(){
        return KEY;
    }
	
    public static String generateKey(){
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(256, new SecureRandom());
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			return Base64.getEncoder().encodeToString(enCodeFormat);
		} catch (Exception e) {
			log.error("", e);
			return null;
		}
    }
    
	public static String encryptAES(String str) {
        try {
			byte[] byteContent = str.getBytes(FbConstant.GLOBAL_ENCODE);
            synchronized (encipher) {
				byte[] result = encipher.doFinal(byteContent);
				return Base64.getEncoder().encodeToString(result);
            }
		} catch (Exception e) {
			log.error("", e);
			return null;
		}
	}
	
	public static String decryptAES(String str) {
        try {
            synchronized (decipher) {
				byte[] result = decipher.doFinal(Base64.getDecoder().decode(str));
				return new String(result, FbConstant.GLOBAL_ENCODE);
			}
		} catch (Exception e) {
			log.error("", e);
			return null;
		}
	}
}
